import Got from 'got'
// import { CronJob } from 'cron'
import * as fs from 'fs'
import WeekMap from './config'

const request = Got.extend({
  headers: {
    'user-agent':
      'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
  }
})

const checkWeekly= async (pids: number[]) => {
  const list = Object.keys(WeekMap)
  const myPids = []
  console.log(pids)
  for (let i = 0; i < list.length; i++) {
    const uri = WeekMap[i + 1].uri
    const { body } = await request(uri + '/issues/latest')
    const $title = body.match(/<title>([^<]+)<\/title>/)[1]
    const pid = $title.match(/( [\d]+):/)[1].trim()
    console.log($title, pid)
    if (Number(pid) > Number(pids[i])) {
      myPids.push(Number(pid))
      await request(`https://ss.leeapps.cn/api/weekly_issue/fetch?cid=${i + 1}&pid=${pid}`)
    } else {
      myPids.push(Number(pids[i]))
    }
  }
  fs.writeFileSync('./latest.txt', JSON.stringify(myPids))
  setTimeout(() => readLatest(), 3*1000*60*60)
}

const readLatest = () => {
  fs.readFile('./latest.txt', 'utf8', (err, data) => {
    if (!err) {
      const list = JSON.parse(data) as number[]
      checkWeekly(list)
    }
  })
}

// const job = new CronJob('0 0 * * * *', function() {
//   console.log('每个小时请求更新');
//   // readLatest()
// }, null, true, 'America/Los_Angeles');
// job.start();

readLatest()
